package com.wyx.SpringSecurityConfig;

import com.wyx.exceptionhandler.MyException;
import com.wyx.utils.CommonResult;
import com.wyx.utils.TokenManager;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class TokenAuthFilter extends BasicAuthenticationFilter {


    private RedisTemplate redisTemplate;

    private AuthenticationManager authenticationManager;

    public TokenAuthFilter(AuthenticationManager authenticationManager, RedisTemplate redisTemplate) {
        super(authenticationManager);
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取当前认证成功用户权限信息
        UsernamePasswordAuthenticationToken authRequest = getAuthentication(request);
        //判断如果有权限信息，放到权限上下文中
        if(authRequest != null) {
            SecurityContextHolder.getContext().setAuthentication(authRequest);
        }
        chain.doFilter(request,response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        //从header获取token
        String token = request.getHeader("token");
        if(token != null) {
            HashMap tokenMap = null;
            try {
                tokenMap = TokenManager.jwtDecrypt(token);
            }catch (RuntimeException e){
                logger.error("令牌已过期");
                return null;
            }
            String username = (String) tokenMap.get("username");
            if (!redisTemplate.opsForValue().get(username).equals(token)){
                System.out.println(token);
                System.out.println(redisTemplate.opsForValue().get(username));
                logger.error("令牌错误");
                return null;
            }
            ArrayList roles = (ArrayList) tokenMap.get("roles");
            StringBuilder authRoles = new StringBuilder();
            for (Object role : roles) {
                role = "ROLE_"+role.toString();
                authRoles.append(role);
                authRoles.append(",");
            }
            // 消除最后一个分号
            authRoles.replace(authRoles.length()-1,authRoles.length(),"");

/*
            //从redis获取对应权限列表
            List<String> permissionValueList = (List<String>)redisTemplate.opsForValue().get(username);
            Collection<GrantedAuthority> authority = new ArrayList<>();
            for(String permissionValue : permissionValueList) {
                SimpleGrantedAuthority auth = new SimpleGrantedAuthority(permissionValue);
                authority.add(auth);
            }*/
            List<GrantedAuthority> authorityList = AuthorityUtils.commaSeparatedStringToAuthorityList(String.valueOf(authRoles));
//            return new UsernamePasswordAuthenticationToken(tokenMap.get("username"),token,authority);
            // 已经通过令牌认证成功，密码设置为空即可
            User user = new User(username,"",authorityList);
            return new UsernamePasswordAuthenticationToken(user,token,authorityList);
        }
        return null;
    }

}
